package com.gopay.bis.nbcb.ebank.operation;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.nbcb.ebank.NbcbB2cMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;
import com.infosec.NetSignServer;

public class NbcbB2cCertHelper implements ICertHelper {

	public String sign(BaseMessage bsaeMessage) throws GopayException {
		try {
			NetSignServer nss = new NetSignServer(); // 构造签名实例
			NbcbB2cMessage messageB2c = (NbcbB2cMessage) bsaeMessage;
			String sourceMsg = messageB2c.getPlainMessage(); // 待签数据，原文
			String bankDN = "C=CN,O=CFCA Operation CA2,OU=NBCB,OU=Enterprises,CN=041@8110000013568276@国付宝信息科技有限公司@00000001"; // 指定签名使用的证书
			BankLogUtils.printB2CSignPlainLog(messageB2c);
			nss.NSSetPlainText(sourceMsg.getBytes("UTF-8")); // 初始化待签数据
			byte bSignMsg[] = nss.NSDetachedSign(bankDN); // 签名，生成二进制的签名数据
			int i = -1; // 返回签名结果，0表示签名成功
			i = nss.getLastErrnum();
			String merSignMsg="";
			if(i==0){
			    merSignMsg = new String(bSignMsg, "UTF-8"); // 得到签名数据
			}
			BankLogUtils.printB2CSignSignatureLog(messageB2c, merSignMsg);
			return merSignMsg;
		} catch (Exception e) {
			BankLogUtils.printB2CSignExceptionLog(bsaeMessage, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6029);
		}
	}

	public Object verify(BaseMessage bsaeMessage) throws GopayException {
		try {
			NetSignServer nss = new NetSignServer();// 构造验签实例
			NbcbB2cMessage messageB2c = (NbcbB2cMessage) bsaeMessage;
			String sourceMsg = messageB2c.getPlainMessage(); // 待签数据，原文
			String signMsg = messageB2c.getSignMessage();
			BankLogUtils.printB2CVerifyPlainLog(messageB2c);
			BankLogUtils.printB2CVerifySignatureLog(messageB2c, messageB2c.getSignMessage());	
			// 验签（signMsg为签名后的数据，sourceMsg为源数据）
			nss.NSDetachedVerify(signMsg.getBytes("UTF-8"),sourceMsg.getBytes("UTF-8"));
			int veriyCode = -1;
			veriyCode = nss.getLastErrnum(); // 得到验签结果
			if (veriyCode != 0) {
				BankLogUtils.printB2CVerifyResultLog(bsaeMessage, false);
				return false;
			}
			return true;
		} catch (Exception e) {
			BankLogUtils.printB2CVerifyExceptionLog(bsaeMessage, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6031);
		}
	}

}
